<template>
  <div class="main-box">
    <div v-loading="treeFilterData.length === 0">
      <TreeFilter
        label="name"
        :title="$t('jggl.jgsz.departmentList')"
        :data="treeFilterData"
        :default-value="initParam.departmentId"
        @change="changeTreeFilter"
      />
    </div>
    <el-tabs v-model="activeName" class="card">
      <div v-auth="'view'">
        <el-tab-pane :label="$t('jggl.jgsz.currentOrg')" name="first">
          <el-form ref="ruleFormRef" :rules="rules" :model="formData" style="width: 1400px" label-width="240px">
            <el-form-item :label="$t('jggl.jgsz.orgType') + ' :'">
              <el-select v-model="formData.actionType" disabled>
                <el-option :label="$t('jggl.jgsz.companyInfo')" value="company" />
                <el-option :label="$t('jggl.jgsz.innerServiceOrg')" value="innerPanel" />
                <el-option :label="$t('jggl.jgsz.serviceOrg')" value="servicePanel" />
                <el-option :label="$t('jggl.jgsz.serviceOrg2')" value="services" />
              </el-select>
            </el-form-item>
            <el-form-item :label="$t('jggl.jgsz.orgName') + ' :'">
              <el-input v-model="formData.orgName" />
            </el-form-item>
            <el-form-item :label="$t('jggl.jgsz.orgPhone') + ' :'" prop="officePhone">
              <el-input v-model="formData.officePhone" />
            </el-form-item>
            <el-form-item :label="$t('jggl.jgsz.fax') + ' :'" prop="officeFax">
              <el-input v-model="formData.officeFax" />
            </el-form-item>
            <el-form-item :label="$t('jggl.jgsz.email') + ' :'" prop="email">
              <el-input v-model="formData.email" />
            </el-form-item>
            <el-form-item :label="$t('jggl.jgsz.address') + ' :'">
              <el-input v-model="formData.address" />
            </el-form-item>
            <el-form-item :label="$t('jggl.jgsz.leader') + ' :'">
              <el-input v-model="formData.personInChargeName" :disabled="true" />
              <span @click="dialogTableVisible = true">
                <el-icon>
                  <EditPen />
                </el-icon>
                {{ $t("jggl.jgsz.selectLeader") }}
              </span>
              <span @click="chearpersonInCharge()">
                <el-icon><CircleCloseFilled></CircleCloseFilled></el-icon>{{ $t("jggl.jgsz.clearLeader") }}
              </span>
            </el-form-item>
            <div v-auth="'edit'">
              <el-form-item>
                <el-button type="primary" @click="onSubmit(ruleFormRef)">{{ $t("jggl.jgsz.save") }}</el-button>
              </el-form-item>
            </div>
          </el-form>
          <el-dialog :title="$t('jggl.jgsz.selectUser')" v-model="dialogTableVisible">
            <div :style="{ height: '500px' }">
              <TreeFilter2 @send-data="sendData" />
            </div>
          </el-dialog>
        </el-tab-pane>
      </div>
      <div v-auth="'add'">
        <el-tab-pane :label="$t('jggl.jgsz.addOrg')" name="second" style="width: 1400px" label-width="120px">
          <el-form ref="addRuleFormRef" :rules="rules" :model="addFormData" label-width="240px">
            <el-form-item :label="$t('jggl.jgsz.orgType') + ' :'">
              <el-select v-model="addFormData.actionType" placeholder="Select">
                <el-option
                  v-for="item in addOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                  :disabled="item.disabled"
                />
              </el-select>
            </el-form-item>
            <el-form-item :label="$t('jggl.jgsz.orgName') + ' :'">
              <el-input v-model="addFormData.orgName" />
            </el-form-item>
            <el-form-item :label="$t('jggl.jgsz.orgPhone') + ' :'" prop="officePhone">
              <el-input v-model="addFormData.officePhone" />
            </el-form-item>
            <el-form-item :label="$t('jggl.jgsz.fax') + ' :'" prop="officeFax">
              <el-input v-model="addFormData.officeFax" />
            </el-form-item>
            <el-form-item :label="$t('jggl.jgsz.email') + ' :'" prop="email">
              <el-input v-model="addFormData.email" />
            </el-form-item>
            <el-form-item :label="$t('jggl.jgsz.address') + ' :'">
              <el-input v-model="addFormData.address" />
            </el-form-item>
            <el-form-item :label="$t('jggl.jgsz.leader') + ' :'">
              <el-input v-model="addFormData.personInChargeName" :disabled="true" />
              <span @click="dialogTableVisibleAddFormData = true">
                <el-icon>
                  <EditPen />
                </el-icon>
                {{ $t("jggl.jgsz.selectLeader") }}
              </span>
              <span @click="chearpersonInChargeAddFormData()">
                <el-icon> <CircleCloseFilled></CircleCloseFilled></el-icon>{{ $t("jggl.jgsz.clearLeader") }}
              </span>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="onSubmitAddFormData(addRuleFormRef)">{{ $t("jggl.jgsz.save") }}</el-button>
            </el-form-item>
          </el-form>
          <el-dialog :title="$t('jggl.jgsz.selectUser')" v-model="dialogTableVisibleAddFormData">
            <div :style="{ height: '500px' }">
              <TreeFilter2 @send-data="sendDataAddFrom" />
            </div>
          </el-dialog>
        </el-tab-pane>
      </div>
      <div v-auth="'view'">
        <el-tab-pane :label="$t('jggl.jgsz.listView')" style="width: 1400px" name="third">
          <ProTable
            ref="proTable"
            row-key="id"
            :indent="20"
            :columns="columns"
            :request-api="getUserDepartmentList"
            :request-auto="false"
            :init-param="initParam"
            :data-callback="dataCallback"
            :search-col="{ xs: 1, sm: 1, md: 2, lg: 3, xl: 3 }"
          >
            <!-- 表格操作 -->
            <template #operation="scope">
              <el-button type="primary" link v-auth="'edit'" :icon="EditPen" @click="editOrg($t('jggl.jgsz.edit'), scope.row)">{{
                $t("jggl.jgsz.edit")
              }}</el-button>
              <el-button type="primary" link v-auth="'delete'" :icon="Delete" @click="deleteAccount(scope.row)">{{
                $t("jggl.jgsz.delete")
              }}</el-button>
            </template>
          </ProTable>
          <el-dialog :title="$t('jggl.jgsz.selectUser')" v-model="dialogEditOrg">
            <el-form ref="editRuleFormRef" :rules="rules" :model="editFormData" label-width="120px">
              <el-form-item :label="$t('jggl.jgsz.orgType') + ' :'">
                <el-select v-model="editFormData.actionType" disabled>
                  <el-option :label="$t('jggl.jgsz.companyInfo')" value="company" />
                  <el-option :label="$t('jggl.jgsz.innerServiceOrg')" value="innerPanel" />
                  <el-option :label="$t('jggl.jgsz.serviceOrg')" value="servicePanel" />
                  <el-option :label="$t('jggl.jgsz.serviceOrg2')" value="services" />
                </el-select>
              </el-form-item>
              <el-form-item :label="$t('jggl.jgsz.orgName') + ' :'">
                <el-input v-model="editFormData.orgName" />
              </el-form-item>
              <el-form-item :label="$t('jggl.jgsz.orgPhone') + ' :'" prop="officePhone">
                <el-input v-model="editFormData.officePhone" />
              </el-form-item>
              <el-form-item :label="$t('jggl.jgsz.fax') + ' :'" prop="officeFax">
                <el-input v-model="editFormData.officeFax" />
              </el-form-item>
              <el-form-item :label="$t('jggl.jgsz.email') + ' :'" prop="email">
                <el-input v-model="editFormData.email" />
              </el-form-item>
              <el-form-item :label="$t('jggl.jgsz.address') + ' :'">
                <el-input v-model="editFormData.address" />
              </el-form-item>
              <el-form-item :label="$t('jggl.jgsz.leader') + ' :'">
                <el-input v-model="editFormData.personInChargeName" :disabled="true" />
                <span @click="dialogTableVisibleEditFormData = true">
                  <el-icon>
                    <EditPen />
                  </el-icon>
                  {{ $t("jggl.jgsz.selectLeader") }}
                </span>
                <span @click="chearpersonInChargeEditFrom()">
                  <el-icon> <CircleCloseFilled> </CircleCloseFilled></el-icon>{{ $t("jggl.jgsz.clearLeader") }}
                </span>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="onSubmitEditFrom(editRuleFormRef)">{{ $t("jggl.jgsz.save") }}</el-button>
              </el-form-item>
              <el-dialog :title="$t('jggl.jgsz.selectUser')" v-model="dialogTableVisibleEditFormData">
                <TreeFilter2 @send-data="sendDataEditFrom" />
              </el-dialog>
            </el-form>
          </el-dialog>
        </el-tab-pane>
      </div>
      <div v-auth="'STST'">
        <el-tab-pane :label="$t('jggl.jgsz.serviceTime')" style="width: 1400px" name="fore">
          <el-form :model="fwsjData" style="width: 360px" label-width="150px">
            <el-form-item class="item" :label="$t('jggl.jgsz.workingHours') + ' :'">
              <el-radio v-model="fwsjData.alldaylabel" label="true">{{ $t("jggl.jgsz.allDay") }}</el-radio>
              <el-radio v-model="fwsjData.alldaylabel" label="false">{{ $t("jggl.jgsz.selectWorkingHours") }}</el-radio>
            </el-form-item>
            <el-form-item class="item">
              <el-form v-if="fwsjData.alldaylabel == 'false'" style="width: 360px" label-width="150px">
                <el-form-item :label="$t('jggl.jgsz.morningStart') + ' :'">
                  <div class="example-basic">
                    <el-time-picker
                      v-model="start"
                      :disabled-seconds="disabledSeconds"
                      :placeholder="$t('jggl.jgsz.selectMorningStart')"
                    />
                  </div>
                </el-form-item>
                <el-form-item :label="$t('jggl.jgsz.morningEnd') + ' :'">
                  <div class="example-basic">
                    <el-time-picker
                      v-model="startNoon"
                      :disabled-seconds="disabledSeconds"
                      :placeholder="$t('jggl.jgsz.selectMorningEnd')"
                    />
                  </div>
                </el-form-item>
                <el-form-item :label="$t('jggl.jgsz.afternoonStart') + ' :'">
                  <div class="example-basic">
                    <el-time-picker
                      v-model="endNoon"
                      :disabled-seconds="disabledSeconds"
                      :placeholder="$t('jggl.jgsz.selectAfternoonStart')"
                    />
                  </div>
                </el-form-item>
                <el-form-item :label="$t('jggl.jgsz.afternoonEnd') + ' :'">
                  <div class="example-basic">
                    <el-time-picker
                      v-model="end"
                      :disabled-seconds="disabledSeconds"
                      :placeholder="$t('jggl.jgsz.selectAfternoonEnd')"
                    />
                  </div>
                </el-form-item>
              </el-form>
            </el-form-item>
          </el-form>
          <el-form :model="fwsjData" style="width: 360px" label-width="150px">
            <el-form-item class="item" :label="$t('jggl.jgsz.workdays') + ' :'">
              <el-radio v-model="fwsjData.gzr" label="true" @click="selectAll()">{{ $t("jggl.jgsz.selectAll") }}</el-radio>
              <el-radio v-model="fwsjData.gzr" label="false" @click="selectUsually()">{{ $t("jggl.jgsz.commonTime") }}</el-radio>
            </el-form-item>
            <el-form-item class="item">
              <el-checkbox v-model="fwsjData.monday" :label="$t('jggl.jgsz.monday')" size="large" />
              <el-checkbox v-model="fwsjData.tuesday" :label="$t('jggl.jgsz.tuesday')" size="large" />
              <el-checkbox v-model="fwsjData.wednesday" :label="$t('jggl.jgsz.wednesday')" size="large" />
              <el-checkbox v-model="fwsjData.thursday" :label="$t('jggl.jgsz.thursday')" size="large" />
              <el-checkbox v-model="fwsjData.friday" :label="$t('jggl.jgsz.friday')" size="large" />
              <el-checkbox v-model="fwsjData.saturday" :label="$t('jggl.jgsz.saturday')" size="large" />
              <el-checkbox v-model="fwsjData.sunday" :label="$t('jggl.jgsz.sunday')" size="large" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="onSubmitfwsjData(fwsjData)">{{ $t("jggl.jgsz.save") }}</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </div>
      <div v-auth="'HDMG'">
        <el-tab-pane :label="$t('jggl.jgsz.holidays')" style="width: 1400px" name="fire">
          <ProTable
            ref="proTableHoliday"
            row-key="id"
            :indent="20"
            :columns="columnsHoliday"
            :request-api="getHolidayList"
            :request-auto="true"
            :init-param="initParamHoliday"
            :data-callback="dataCallbackHoliday"
            :search-col="{ xs: 1, sm: 1, md: 2, lg: 3, xl: 3 }"
          >
            <!-- 表格操作 -->
            <template #operation="scope">
              <el-button type="primary" link :icon="EditPen" @click="editHoliday($t('jggl.jgsz.edit'), scope.row)">{{
                $t("jggl.jgsz.edit")
              }}</el-button>
              <el-button type="primary" link :icon="Delete" @click="deleteHoliday(scope.row)">{{
                $t("jggl.jgsz.delete")
              }}</el-button>
            </template>
          </ProTable>
        </el-tab-pane>
      </div>
    </el-tabs>
  </div>
</template>

<script setup lang="tsx" name="treeProTable">
import { onMounted, reactive, ref } from "vue";
import { User, OrgManager } from "@/api/interface";
import { genderType } from "@/utils/dict";
import { useHandleData } from "@/hooks/useHandleData";
import { ElMessage, ElNotification, FormInstance, FormRules } from "element-plus";
import ProTable from "@/components/ProTable/index.vue";
import TreeFilter from "@/components/TreeFilter/index.vue";
import ImportExcel from "@/components/ImportExcel/index.vue";
import UserDrawer from "@/views/proTable/components/UserDrawer.vue";
import { CirclePlus, Delete, EditPen, View } from "@element-plus/icons-vue";
import { ColumnProps, ProTableInstance } from "@/components/ProTable/interface";
import { getUserTreeList, deleteUser, editUser, addUser, getUserStatus } from "@/api/modules/user";
import TreeFilter2 from "@/views/tools/userselect/index.vue";
import { isTelOrFax, isEmail } from "@/utils/eleValidate";
import { ElMessageBox } from "element-plus";
import {
  updateOrg,
  save,
  isCategoryExisted,
  getUserDepartmentList,
  updateOrgWin,
  deleteOrgs,
  findServiceTimeByOrgNo,
  saveOrgUpdate,
  getHolidayList,
  findAllSun,
  getUserDepartment
} from "@/api/modules/jggl";
import { useAuthButtons } from "@/hooks/useAuthButtons";
import { useI18n } from "vue-i18n";
import { useUserStore } from "@/stores/modules/user";
const userStore = useUserStore();
const { BUTTONS } = useAuthButtons();
const { t } = useI18n();

onMounted(() => {
  getTreeFilter();
  // ElNotification({
  //   title: "温馨提示",
  //   message: "该页面 ProTable 数据不会自动请求，需等待 treeFilter 数据请求完成之后，才会触发表格请求。",
  //   type: "info",
  //   duration: 10000
  // });
  // setTimeout(() => {
  //   ElNotification({
  //     title: "温馨提示",
  //     message: "该页面 ProTable 性别搜索框为远程数据搜索，详情可查看代码。",
  //     type: "info",
  //     duration: 10000
  //   });
  // }, 0);
});

let start = ref(new Date(2016, 9, 10, 8, 0));
let startNoon = ref(new Date(2016, 9, 10, 12, 0));
let endNoon = ref(new Date(2016, 9, 10, 14, 0));
let end = ref(new Date(2016, 9, 10, 18, 0));
const makeRange = (start: number, end: number) => {
  const result: number[] = [];
  for (let i = start; i <= end; i++) {
    result.push(i);
  }
  return result;
};
const disabledSeconds = (hour: number, minute: number) => {
  return makeRange(1, 59);
};

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({ departmentId: "", page: 1, rows: 10 });
const initParamHoliday = reactive({ departmentId: "", page: 1, rows: 10 });
// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total && pageNum && pageSize 这些字段，可以在这里进行处理成这些字段
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行
const dataCallback = (data: any) => {
  return {
    list: data.data,
    total: data.totalSize,
    pageNum: data.page,
    pageSize: data.rows
  };
};

const dataCallbackHoliday = (data: any) => {
  return {
    list: data.data,
    total: data.totalSize,
    pageNum: data.page,
    pageSize: data.rows
  };
};
const ruleFormRef = ref<FormInstance>();
// do not use same name with ref
const formData = reactive({
  actionType: "",
  doTag: "edit",
  orgType: "",
  orgName: "",
  officePhone: "",
  officeFax: "",
  email: "",
  address: "",
  personInChargeName: "",
  personInChargeNo: "",
  orgNo: "",
  parentOrgNo: ""
});
const fwsjData = reactive({
  alldaylabel: "true",
  startHour: 0,
  startMinute: 0,
  startNoonHour: 0,
  startNoonMinute: 0,
  endNoonHour: 0,
  endNoonMinute: 0,
  endHour: 0,
  endMinute: 0,
  workDayQuickSelect: "on",
  monday: true,
  tuesday: true,
  wednesday: true,
  thursday: true,
  friday: true,
  saturday: true,
  sunday: true,
  allday: true,
  sid: "",
  orgNo: "",
  gzr: ""
});

const addRuleFormRef = ref<FormInstance>();
const editRuleFormRef = ref<FormInstance>();
// do not use same name with ref
const addFormData = reactive({
  actionType: "services",
  doTag: "add",
  orgType: "",
  orgName: "",
  officePhone: "",
  officeFax: "",
  email: "",
  address: "",
  personInChargeName: "",
  personInChargeNo: "",
  orgNo: "",
  parentOrgNo: ""
});

// do not use same name with ref
const editFormData = reactive({
  actionType: "",
  doTag: "edit",
  orgType: "",
  orgName: "",
  officePhone: "",
  officeFax: "",
  email: "",
  address: "",
  personInChargeName: "",
  personInChargeNo: "",
  orgNo: "",
  parentOrgNo: ""
});
const addOptions = reactive([
  {
    value: "services",
    label: "服务机构",
    disabled: false
  },
  {
    value: "inner",
    label: "被服务机构",
    disabled: false
  }
]);

const activeName = ref("first");

const dialogEditOrg = ref(false);
const dialogTableVisible = ref(false);
const dialogTableVisibleAddFormData = ref(false);
const dialogTableVisibleEditFormData = ref(false);
const onSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (formData.orgNo.toString() == "1") {
      ElMessage.error(t("jggl.jgsz.systemDefaultDataNotAllowed"));
    } else {
      if (valid) {
        updateOrg(formData, "organizationDto").then(res => {
          ElMessage.success(t("common.saveSuccess"));
          userStore.setDepartmentTree([]);
          getTreeFilter();
        });
      } else {
        ElMessage.error(t("common.pleaseFillFormCorrectly"));
      }
    }
  });
};
const onSubmitAddFormData = async (formEl: FormInstance | undefined) => {
  if (addFormData.orgName == "") {
    ElMessage.error(t("jggl.jgsz.orgNameCannotBeEmpty"));
    return;
  }
  // if(addFormData.personInChargeName==""){
  // 	ElMessage.error("组长不能为空");
  // 	return
  // }
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      isCategoryExisted(addFormData, "organizationDto").then(res => {
        if (res.toString() == "isExist") {
          ElMessage.error(t("jggl.jgsz.orgAlreadyExists"));
        } else {
          save(addFormData, "organizationDto").then(res => {
            ElMessage.success(t("jggl.jgsz.addOrgSuccess"));
            userStore.setDepartmentTree([]);
            getTreeFilter();
          });
        }
      });
    } else {
      ElMessage.error(t("common.pleaseFillFormCorrectly"));
    }
  });
};
const onSubmitEditFrom = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      isCategoryExisted(editFormData, "organizationDto").then(res => {
        if (res.toString() == "isExist") {
          ElMessage.error(t("jggl.jgsz.orgAlreadyExists"));
        } else {
          updateOrgWin(editFormData, "organizationDto").then(res => {
            ElMessage.success(t("jggl.jgsz.updateOrgSuccess"));
            userStore.setDepartmentTree([]);
            getTreeFilter();
            dialogEditOrg.value = false;
            proTable.value?.getTableList();
          });
        }
      });
    } else {
      ElMessage.error(t("common.pleaseFillFormCorrectly"));
    }
  });
};

const selectAll = () => {
  fwsjData.monday = true;
  fwsjData.thursday = true;
  fwsjData.tuesday = true;
  fwsjData.wednesday = true;
  fwsjData.friday = true;
  fwsjData.saturday = true;
  fwsjData.sunday = true;
};
const selectUsually = () => {
  fwsjData.monday = true;
  fwsjData.thursday = true;
  fwsjData.tuesday = true;
  fwsjData.wednesday = true;
  fwsjData.friday = true;
  fwsjData.saturday = false;
  fwsjData.sunday = false;
};

const onSubmitfwsjData = (param: any) => {
  if (startNoon.value < start.value) {
    ElMessage.error(t("jggl.jgsz.morningEndTimeCannotBeLessThanStart"));
    return;
  } else if (endNoon.value < startNoon.value) {
    ElMessage.error(t("jggl.jgsz.afternoonStartTimeCannotBeLessThanEnd"));
    return;
  } else if (end.value < endNoon.value) {
    ElMessage.error(t("jggl.jgsz.afternoonEndTimeCannotBeLessThanStart"));
    return;
  } else {
    if (fwsjData.alldaylabel != "true") {
      fwsjData.startHour = start.value.getHours();
      fwsjData.startMinute = start.value.getMinutes();
      fwsjData.endHour = end.value.getHours();
      fwsjData.endMinute = end.value.getMinutes();
      fwsjData.startNoonHour = startNoon.value.getHours();
      fwsjData.startMinute = startNoon.value.getMinutes();
      fwsjData.endNoonHour = endNoon.value.getHours();
      fwsjData.endNoonMinute = endNoon.value.getMinutes();
      fwsjData.allday = false;
    } else {
      fwsjData.startHour = 0;
      fwsjData.startMinute = 0;
      fwsjData.endHour = 0;
      fwsjData.endMinute = 0;
      fwsjData.startNoonHour = 0;
      fwsjData.startMinute = 0;
      fwsjData.endNoonHour = 0;
      fwsjData.endNoonMinute = 0;
      fwsjData.allday = true;
    }
    if (fwsjData.orgNo == "") {
      ElMessage.error(t("jggl.jgsz.pleaseSelectOrg"));
      return;
    }
    saveOrgUpdate(fwsjData, "serviceTimeDTO").then(res => {
      if (res != null && res.toString() == "1") {
        ElMessage.success(t("common.saveSuccess"));
      }
    });
  }
};
// 表格配置项
const columns = reactive<ColumnProps<User.ResUserList>[]>([
  { prop: "orgNo", label: t("jggl.jgsz.number") },
  { prop: "orgName", label: t("jggl.jgsz.name") },
  { prop: "officePhone", label: t("jggl.jgsz.orgPhone") },
  { prop: "email", label: t("jggl.jgsz.email") },
  { prop: "address", label: t("jggl.jgsz.address") },
  { prop: "personInChargeName", label: t("jggl.jgsz.leader"), width: 180 },
  { prop: "operation", label: t("common.operation"), width: 300, fixed: "right" }
]);

const columnsHoliday = reactive<ColumnProps<User.ResUserList>[]>([
  { prop: "orgNo", label: t("jggl.jgsz.date") },
  { prop: "orgName", label: t("jggl.jgsz.description") },
  { prop: "orgName", label: t("jggl.jgsz.belongOrg") },
  { prop: "operation", label: t("common.operation"), width: 300, fixed: "right" }
]);

const rules = reactive<FormRules>({
  orgName: [{ required: true, message: t("jggl.jgsz.pleaseEnterOrgName"), trigger: "blur" }],
  officePhone: [{ required: false, validator: isTelOrFax, trigger: "blur" }],
  officeFax: [{ required: false, validator: isTelOrFax, trigger: "blur" }],
  email: [{ required: false, validator: isEmail, trigger: "blur" }]
});
//子组件弹窗回调方法
const sendData = (data: any) => {
  dialogTableVisible.value = false;
  formData.personInChargeNo = data.userId;
  formData.personInChargeName = data.fullName;
};
//子组件弹窗回调方法
const sendDataAddFrom = (data: any) => {
  dialogTableVisibleAddFormData.value = false;
  addFormData.personInChargeNo = data.userId;
  addFormData.personInChargeName = data.fullName;
};

//子组件弹窗回调方法
const sendDataEditFrom = (data: any) => {
  dialogTableVisibleEditFormData.value = false;
  editFormData.personInChargeNo = data.userId;
  editFormData.personInChargeName = data.fullName;
};
// ProTable 实例
const proTable = ref<ProTableInstance>();

// ProTable 实例
const proTableHoliday = ref<ProTableInstance>();
// 获取 treeFilter 数据
// 当 proTable 的 requestAuto 属性为 false，不会自动请求表格数据，等待 treeFilter 数据回来之后，更改 initParam.departmentId 的值，才会触发请求 proTable 数据
const treeFilterData = ref<any>([]);
const getTreeFilter = async () => {
  const data = await getUserDepartment();
  // 使用traverseTree遍历树
  traverseTree(data[0], node => {
    node.id = node.attr.orgName;
    node.name = node.attr.orgName;
  });
  treeFilterData.value = data;
  initParam.departmentId = data[0].attr.orgNo;
};

const chearpersonInChargeAddFormData = () => {
  addFormData.personInChargeName = "";
  addFormData.personInChargeNo = "";
};
const chearpersonInChargeEditFrom = () => {
  editFormData.personInChargeName = "";
  editFormData.personInChargeNo = "";
};
const chearpersonInCharge = () => {
  formData.personInChargeName = "";
  formData.personInChargeNo = "";
};
// 树形筛选切换
const changeTreeFilter = (val: string) => {
  // 使用traverseTree遍历树
  traverseTree(treeFilterData.value[0], node => {
    if (node.attr.orgName == val) {
      //当前机构表单
      formData.orgName = node.attr.orgName;
      formData.officePhone = node.attr.officePhone;
      formData.officeFax = node.attr.officeFax;
      formData.email = node.attr.email;
      formData.address = node.attr.address;
      formData.personInChargeName = node.attr.personInChargeName == null ? "" : node.attr.personInChargeName;
      formData.personInChargeNo = node.attr.personInChargeNo == null ? "" : node.attr.personInChargeNo;
      formData.orgNo = node.attr.orgNo;
      formData.parentOrgNo = node.attr.parentNo;
      formData.orgType = node.attr.orgType;
      formData.actionType = node.attr.orgType;

      //新增机构表单
      addFormData.parentOrgNo = node.attr.orgNo == null ? 1 : node.attr.orgNo;
      addFormData.orgType = node.attr.orgType == null ? "" : node.attr.orgType;
      addFormData.actionType = node.attr.orgType == "servicePanel" || node.attr.orgType == "services" ? "services" : "inner";
      if (node.attr.orgType == "company") {
        addOptions[0].disabled = false;
        addOptions[1].disabled = false;
      } else {
        addOptions[0].disabled = true;
        addOptions[1].disabled = true;
      }

      findServiceTimeByOrgNo(node.attr.orgNo).then(newParams => {
        let res = JSON.parse(JSON.stringify(newParams));

        fwsjData.sid = res.sid;
        fwsjData.endHour = res.endHour;
        fwsjData.endMinute = res.endMinute;
        fwsjData.endNoonHour = res.endNoonHour;
        fwsjData.endNoonMinute = res.endNoonMinute;
        fwsjData.friday = res.friday;
        fwsjData.monday = res.monday;
        fwsjData.orgNo = node.attr.orgNo;
        fwsjData.saturday = res.saturday;
        fwsjData.allday = res.allday;
        fwsjData.alldaylabel = res.allday ? "true" : "false";
        fwsjData.startHour = res.startHour;
        fwsjData.startMinute = res.startMinute;
        fwsjData.startNoonHour = res.startNoonHour;
        fwsjData.startNoonMinute = res.startNoonMinute;
        fwsjData.sunday = res.sunday;
        fwsjData.thursday = res.thursday;
        fwsjData.tuesday = res.tuesday;
        fwsjData.wednesday = res.wednesday;
        if (!res.allday) {
          start.value = new Date(2016, 9, 10, res.startHour, res.startMinute);
          startNoon.value = new Date(2016, 9, 10, res.startNoonHour, res.startNoonMinute);
          endNoon.value = new Date(2016, 9, 10, res.endNoonHour, res.endNoonMinute);
          end.value = new Date(2016, 9, 10, res.endHour, res.endMinute);
        } else {
          // console.log("dddata："+JSON.stringify(fwsjData))
        }
      });
    }
  });
  initParam.departmentId = val;
};

// 模拟远程加载性别搜索框数据
const loading = ref(false);
const filterGenderEnum = ref<typeof genderType>([]);
const remoteMethod = (query: string) => {
  filterGenderEnum.value = [];
  if (!query) return;
  loading.value = true;
  setTimeout(() => {
    loading.value = false;
    filterGenderEnum.value = genderType.filter(item => item.label.includes(query));
  }, 500);
};

const editOrg = (title: string, row: any = {}) => {
  dialogEditOrg.value = true;
  //当前机构表单
  editFormData.orgName = row.orgName;
  editFormData.officePhone = row.officePhone;
  editFormData.officeFax = row.officeFax;
  editFormData.email = row.email;
  editFormData.address = row.address;
  editFormData.personInChargeName = row.personInChargeName == null ? "" : row.personInChargeName;
  editFormData.personInChargeNo = row.personInChargeNo == null ? "" : row.personInChargeNo;
  editFormData.orgNo = row.orgNo;
  editFormData.parentOrgNo = row.parentNo;
  editFormData.orgType = row.orgType;
  editFormData.actionType = row.orgType;
};

const editHoliday = (title: string, row: any = {}) => {
  ElMessage({
    type: "success",
    message: t("jggl.jgsz.editHoliday")
  });
};

const deleteHoliday = (title: string, row: any = {}) => {
  ElMessage({
    type: "success",
    message: t("jggl.jgsz.deleteHoliday")
  });
};
// 删除用户信息
const deleteAccount = async (params: OrgManager.ReqOrgManagerParams) => {
  ElMessageBox.confirm(t("jggl.jgsz.confirmDeleteOrg", { name: params.orgName }), t("common.confirmDelete"), {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
    center: true
  })
    .then(() => {
      deleteOrgs({ orgNos: params.orgNo }).then(res => {
        ElMessage({
          type: "success",
          message: "删除成功"
        });
        proTable.value?.getTableList();
        getTreeFilter();
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除"
      });
    });
  // await useHandleData(deleteOrgs, { orgNos: params.orgNo }, `删除【${params.orgName}】部门`);
};

interface TreeNode {
  value: any;
  children?: TreeNode[];
  id: string;
  name: string;
  attr: any;
}

function traverseTree(node: TreeNode, callback: (node: TreeNode) => void) {
  callback(node);
  if (node.children) {
    node.children.forEach(child => traverseTree(child, callback));
  }
}
</script>
